/*
Copyright 2020 The Skaffold Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package deploy

import (
	"bytes"
	"fmt"
	"io"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/color"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/logfile"
)

// TimeFormat is used to name log files generated by deploy step
const TimeFormat = "2006-01-02_15-04-05"

type Muted interface {
	MuteDeploy() bool
}

// WithLogFile returns a multiwriter that writes both to a file and a buffer, with the buffer being written to the provided output buffer in case of error
func WithLogFile(filename string, out io.Writer, muted Muted) (io.Writer, func(error), error) {
	if !muted.MuteDeploy() {
		return out, func(error) {}, nil
	}

	file, err := logfile.Create("deploy", filename)
	if err != nil {
		return out, func(error) {}, fmt.Errorf("unable to create log file for deploy step: %w", err)
	}

	color.Default.Fprintln(out, "Starting deploy...")
	fmt.Fprintln(out, "- writing logs to", file.Name())

	// Print logs to a memory buffer and to a file.
	var buf bytes.Buffer
	w := io.MultiWriter(file, &buf)

	// After the deploy finishes, close the log file. If the deploy failed, print the full log to output buffer.
	return w, func(deployErr error) {
		file.Close()
		if deployErr != nil {
			buf.WriteTo(out)
		}
	}, err
}
